package gov.pbc.nn.kjgl.software.dao;

import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.bstek.dorado.data.entity.EntityState;
import com.bstek.dorado.data.entity.EntityUtils;
import com.bstek.dorado.data.provider.Page;

import gov.pbc.nn.core.dao.AbstractHibernateDao;
import gov.pbc.nn.kjgl.entity.DeclareTime;
import gov.pbc.nn.kjgl.entity.ProjectTask;

@Repository
public class DeclareTimeDao extends AbstractHibernateDao {

	public void loadDeclareTime(Page<DeclareTime> page) {
		DetachedCriteria query = DetachedCriteria.forClass(DeclareTime.class);
		query.add(Restrictions.or(Restrictions.eq("invalid", false),
				Restrictions.isNull("invalid")));
		this.pagingQuery(page, query);
	}

	public void saveDeclareTime(Collection<DeclareTime> declareTime,
			Map<String, Object> parameter) {
		int again = (int) parameter.get("again");

		for (DeclareTime dec : declareTime) {
			if (EntityUtils.getState(dec) == EntityState.NEW) {
				int myYear = dec.getYear();
				Calendar myBeginTime = Calendar.getInstance();
				myBeginTime.setTime(dec.getBeginTime());
				Calendar myEndTime = Calendar.getInstance();
				myEndTime.setTime(dec.getEndTime());
				dec.setYear(myYear);
				dec.setBeginTime(myBeginTime.getTime());
				dec.setEndTime(myEndTime.getTime());
				this.save(dec);
				for (int num = 1; num < again; num++) {
					myYear = (myYear + 1);
					myBeginTime.add(Calendar.YEAR, +1);
					myEndTime.add(Calendar.YEAR, +1);
					dec.setYear(myYear);
					dec.setBeginTime(myBeginTime.getTime());
					dec.setEndTime(myEndTime.getTime());
					this.save(dec);
				}
			} else if (EntityUtils.getState(dec) == EntityState.MODIFIED) {
				this.update(dec);
			}
		}
	}

	public void deleteDeclareTime(List<String> list) {
		for (String id : list) {
			this.delete(id, DeclareTime.class);
		}
	}
}
